//
//  QSOSSUploadHelper.m
//  QSSmarkPark-iOS
//
//  Created by 孙俊 on 2019/3/28.
//  Copyright © 2019 HANGZHOU QISHENG TECHNOLOGY CO.LTD. All rights reserved.
//

#import "QSOSSUploadHelper.h"
#import "QSRequestManager.h"
#import "ResponseMessage.h"
#import <AliyunOSSiOS.h>
#import "TZImagePickerController.h"
@implementation QSOSSUploadHelper

+ (void)asyncUploadFilesToOSS:(NSArray *)files complete:(void (^)(NSArray<NSString *> * _Nullable, NSError * _Nullable))completeBlock {
    [self getOSSAuthAndCompleteBlock:^(ResponseMessage *rspStatusAndMessage, QSOSSAuthModel *ossAuthModel) {
        if (ossAuthModel) {
            if (![ossAuthModel.SystemOssEndpoint hasPrefix:@"http"]) {
                ossAuthModel.SystemOssEndpoint = [NSString stringWithFormat:@"http://%@",ossAuthModel.SystemOssEndpoint];
            }
            id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:ossAuthModel.AccessKeyId secretKeyId:ossAuthModel.AccessKeySecret securityToken:ossAuthModel.SecurityToken];
            OSSClientConfiguration * conf = [OSSClientConfiguration new];
            // 网络请求遇到异常失败后的重试次数
            conf.maxRetryCount = 3;
            // 网络请求的超时时间
            conf.timeoutIntervalForRequest = 60;
            // 允许资源传输的最长时间
            conf.timeoutIntervalForResource = 24 * 60 * 60;
            OSSClient * client = [[OSSClient alloc] initWithEndpoint:ossAuthModel.SystemOssEndpoint credentialProvider:credential clientConfiguration:conf];
            
            NSOperationQueue *queue = [[NSOperationQueue alloc] init];
            queue.maxConcurrentOperationCount = files.count;
            
            NSMutableArray *callBackNames = [NSMutableArray array];
            int i = 0;
            for (id object in files) {
                if (object) {
                    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
                        //任务执行
                        OSSPutObjectRequest * put = [OSSPutObjectRequest new];
                        put.bucketName = ossAuthModel.SystemOssBucket;
                        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
                        formatter.dateFormat = @"YYYYMMddHHmmssSSS";
                        NSString *dateStr = [formatter stringFromDate:[NSDate date]];
                        NSString *fileName;
                        if ([object isKindOfClass:[UIImage class]]) {
                            fileName = [dateStr stringByAppendingString:@".jpg"];
                            //修正图片
                            [TZImageManager manager].shouldFixOrientation = YES;
                            UIImage *cropedImage = [[TZImageManager manager] fixOrientation:object];
                            //上传
                            NSData *data = [NSData compressImageDataWithImage:cropedImage];
                            put.uploadingData = data;
                        } else if ([object isKindOfClass:[NSURL class]]) {
                            fileName = [dateStr stringByAppendingString:@".mp4"];
                            NSData *data = [NSData dataWithContentsOfURL:object];
                            put.uploadingData = data;
                        }
                        
                        if (ossAuthModel.SystemOssChannelName.length) {
                            put.objectKey =  [NSString stringWithFormat:@"%@/%@",ossAuthModel.SystemOssChannelName, fileName];
                        } else {
                            put.objectKey = fileName;
                        }
                        
                        OSSTask * putTask = [client putObject:put];
                        [putTask waitUntilFinished]; // 阻塞直到上传完成
                        if (!putTask.error) {
                            NSLog(@"upload object success!");
                            NSString *ossFullFileName = [NSString stringWithFormat:@"%@/%@",ossAuthModel.SystemOssEndpoint,put.objectKey];
                            [callBackNames addObject:ossFullFileName];
                        } else {
                            [queue cancelAllOperations];
                            NSLog(@"upload object failed, error: %@" , putTask.error);
                            dispatch_async(dispatch_get_main_queue(), ^{
                                if (completeBlock) {
                                    completeBlock(nil ,putTask.error);
                                }
                            });
                        }
                        if (object == files.lastObject) {
                            dispatch_async(dispatch_get_main_queue(), ^{
                                if (completeBlock) {
                                    completeBlock([NSArray arrayWithArray:callBackNames] ,nil);
                                }
                            });
                        }
                    }];
                    if (queue.operations.count != 0) {
                        [operation addDependency:queue.operations.lastObject];
                    }
                    [queue addOperation:operation];
                }
                i++;
            }
        }
    }];
}

+ (void)getOSSAuthAndCompleteBlock:(void(^)(ResponseMessage *rspStatusAndMessage, QSOSSAuthModel *ossAuthModel))compeleteBlock {
    NSString *requestURL = [kBaseUrlPrefix stringByAppendingString:kGetOSSAuthToken];
    NSMutableDictionary *bodyDict = [NSMutableDictionary dictionaryWithCapacity:0];
    NSString *url = kBaseUrlPrefix;//带入前缀域名
    [bodyDict setObject:url forKey:@"url"];
    
    [QSRequestManager executeTokenGET:requestURL requestBody:bodyDict andBlock:^(ResponseMessage *rspStatusAndMessage, NSDictionary *responseDataDic) {
        QSOSSAuthModel *ossAuthModel;
        if (rspStatusAndMessage.code == kResponseSuccessCode && responseDataDic.allKeys.count) {
            ossAuthModel = [QSOSSAuthModel mj_objectWithKeyValues:responseDataDic];
        }
        if (rspStatusAndMessage.code == kResponseSuccessCode && !responseDataDic.allKeys.count) {
            [QSAppKeyWindow showAutoHideHudWithText:@"服务器开小差了"];
        }
        compeleteBlock(rspStatusAndMessage, ossAuthModel);
    }];
}

@end

@implementation QSOSSAuthModel


@end
